package thorsten.wordlist.parser;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedList;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MultiFileOutputHandler extends DefaultHandler{
	private String buffer = "";
	private long elementWriteCount = 0;
	private long elementCount = 0;
	private String outDir = "o:/output/";
	private long maxElCount = 10000000;

	public MultiFileOutputHandler() {
		super();
	}

	public void add(String data) {
		this.buffer += data;
	}

	public void flush(String outfileName) throws IOException {
//		this.buffer = this.buffer.trim();
//		if(buffer.length() == 0)
//			return;
//		
		if (this.elementWriteCount >= this.maxElCount){
			this.buffer = "";
			return;
		}
		
		Writer outfile;
		outfile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfileName), "UTF-8"));
		outfile.write(this.buffer);
		outfile.close();
		this.elementWriteCount++;
		this.buffer = "";
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
//		String s=new String(ch);
//		s = s.substring(start, start + length);
		
		String s = new String(ch, start, length);
		
		this.add(s);
		
		super.characters(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		try {
			this.flush(this.outDir + String.format("%0" + 10 + "d", this.elementWriteCount));
			this.elementCount++;
			if(this.elementCount % 10000 == 0)
				System.out.println(this.elementCount);
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.endElement(uri, localName, qName);
	}
	

	@Override
	public void endDocument() throws SAXException {
		System.out.println("Dokument beendet");
		System.out.println(this.elementWriteCount + " Elemente geschrieben");
		System.out.println(this.elementCount + " Elemente gesamt");
		super.endDocument();
	}


}
